from django import forms
from timeholder.forms.bootstrap import BootStrap

from timeholder import models
from django.core.exceptions import ValidationError

from django.contrib.admin.widgets import AdminDateWidget


class ProjectModelForm(BootStrap, forms.ModelForm):
    class Meta:
        model = models.Task
        fields = ['username', 'name', 'start_datetime', 'end_datetime','text']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'text':forms.Textarea(attrs={'class': 'form-control'}),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        # 校验项目是否存在 ()
        exists = models.Task.objects.filter(name=name, username=self.request.user_obj.username).exists()
        if exists:
            raise ValidationError('项目名已存在')
        return name
